{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## 使用 `czsc` 进行选股\n",
    "---\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.5.8\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "sys.path.insert(0, \".\")\n",
    "sys.path.insert(0, \"..\")\n",
    "\n",
    "import czsc\n",
    "print(czsc.__version__)\n",
    "\n",
    "from datetime import datetime\n",
    "from typing import List\n",
    "import traceback\n",
    "from tqdm import tqdm\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from tqdm import tqdm_notebook as tqdm\n",
    "from czsc.analyze import KlineAnalyze"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "### 笔中枢三买选股\n",
    "---\n",
    "\n",
    "条件描述： 最近五笔走势，前三笔构成中枢，第四笔离开中枢，第五笔向下不回中枢\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def selector_bi01(kline):\n",
    "    \"\"\"笔中枢三买选股\"\"\"\n",
    "    res = {\"is_match\": False, \"notes\": None, \"dt\": None, \"price\": None,\n",
    "       \"name\": \"selector_bi01\", \"symbol\": None, \"desc\": \"笔中枢三买选股\"}\n",
    "    try:\n",
    "        ka = KlineAnalyze(kline, ma_params=(5, 34, 120, 233), bi_mode=\"new\")\n",
    "        points = ka.bi_list[-6:]\n",
    "\n",
    "        if len(points) == 6 and points[-1]['fx_mark'] == \"d\":\n",
    "            zs_g = min([x['bi'] for x in points[:4] if x['fx_mark'] == 'g'])\n",
    "            zs_d = max([x['bi'] for x in points[:4] if x['fx_mark'] == 'd'])\n",
    "\n",
    "            if points[-1]['bi'] > zs_g > zs_d:\n",
    "                res['symbol'] = ka.symbol\n",
    "                res['is_match'] = True\n",
    "                res['dt'] = ka.end_dt\n",
    "                res['price'] = ka.latest_price\n",
    "\n",
    "    except:\n",
    "        print(\"{} 分析失败\".format(symbol))\n",
    "        traceback.print_exc()\n",
    "    return res"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 三笔回调构成三买\n",
    "---"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def selector_bi02(kline):\n",
    "    \"\"\"三笔回调构成三买\"\"\"\n",
    "    res = {\"is_match\": False, \"notes\": None, \"dt\": None, \"price\": None,\n",
    "           \"name\": \"selector_bi02\", \"symbol\": None, \"desc\": \"三笔回调构成三买\"}\n",
    "\n",
    "    try:\n",
    "        ka = KlineAnalyze(kline, ma_params=(5, ), bi_mode=\"new\")\n",
    "        if len(ka.bi_list) > 16 and ka.bi_list[-1]['fx_mark'] == 'd':\n",
    "            points = ka.bi_list[-16:]\n",
    "            fd1_points = [x['bi'] for x in points[0: 4]]\n",
    "            fd2_points = [x['bi'] for x in points[3: 7]]\n",
    "            fd3_points = [x['bi'] for x in points[6: 10]]\n",
    "            fd4_points = [x['bi'] for x in points[9: 13]]\n",
    "            fd5_points = [x['bi'] for x in points[12: 16]]\n",
    "            fd1 = {\"high\": max(fd1_points), \"low\": min(fd1_points)}\n",
    "            fd2 = {\"high\": max(fd2_points), \"low\": min(fd2_points)}\n",
    "            fd3 = {\"high\": max(fd3_points), \"low\": min(fd3_points)}\n",
    "            fd4 = {\"high\": max(fd4_points), \"low\": min(fd4_points)}\n",
    "            fd5 = {\"high\": max(fd5_points), \"low\": min(fd5_points)}\n",
    "\n",
    "            zs_g = min(fd1['high'], fd2['high'], fd3['high'])\n",
    "            zs_d = max(fd1['low'], fd2['low'], fd3['low'])\n",
    "            if zs_d < zs_g < fd5['low'] < fd4['high'] and fd4['high'] > max(fd1['high'], fd3['high']):\n",
    "                res['symbol'] = ka.symbol\n",
    "                res['is_match'] = True\n",
    "                res['dt'] = ka.end_dt\n",
    "                res['price'] = ka.latest_price\n",
    "    except:\n",
    "        traceback.print_exc()\n",
    "    return res"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 执行选股\n",
    "---"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5bd5e456ae294b98a5f6a470beafba71",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, description='selector', style=ProgressStyle(description_width='initial')),…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "选股结果：\n",
      "    is_match notes                  dt   price           name       symbol  \\\n",
      "0       True  None 2020-11-17 15:00:00   82.50  selector_bi02  300124.XSHE   \n",
      "1       True  None 2020-11-17 15:00:00   26.35  selector_bi02  300146.XSHE   \n",
      "2       True  None 2020-11-17 15:00:00   44.99  selector_bi02  300274.XSHE   \n",
      "3       True  None 2020-11-17 15:00:00   23.94  selector_bi02  300476.XSHE   \n",
      "4       True  None 2020-11-17 15:00:00   98.20  selector_bi02  300496.XSHE   \n",
      "5       True  None 2020-11-17 15:00:00  302.30  selector_bi02  300661.XSHE   \n",
      "6       True  None 2020-11-17 15:00:00   86.36  selector_bi02  300747.XSHE   \n",
      "7       True  None 2020-11-17 15:00:00   86.36  selector_bi02  300747.XSHE   \n",
      "8       True  None 2020-11-17 15:00:00  250.68  selector_bi02  300750.XSHE   \n",
      "9       True  None 2020-11-17 15:00:00   38.15  selector_bi02  300761.XSHE   \n",
      "10      True  None 2020-11-17 15:00:00  547.96  selector_bi02  300782.XSHE   \n",
      "\n",
      "        desc  \n",
      "0   三笔回调构成三买  \n",
      "1   三笔回调构成三买  \n",
      "2   三笔回调构成三买  \n",
      "3   三笔回调构成三买  \n",
      "4    笔中枢三买选股  \n",
      "5   三笔回调构成三买  \n",
      "6    笔中枢三买选股  \n",
      "7   三笔回调构成三买  \n",
      "8   三笔回调构成三买  \n",
      "9    笔中枢三买选股  \n",
      "10  三笔回调构成三买  \n"
     ]
    }
   ],
   "source": [
    "# 导入聚宽数据\n",
    "from czsc.data.jq import *\n",
    "\n",
    "# 如果是第一次使用需要设置 token\n",
    "# set_token(\"手机号\", \"密码\")\n",
    "\n",
    "# 使用聚宽数据在创业板综指上选股\n",
    "symbols = get_index_stocks(\"399006.XSHE\")\n",
    "freq = \"30min\"\n",
    "\n",
    "results = []\n",
    "for symbol in tqdm(symbols, desc=\"selector\"):\n",
    "    try:\n",
    "        kline = get_kline(symbol, end_date=datetime.now(), freq=freq, count=2000)\n",
    "        for selector in [selector_bi01, selector_bi02]:\n",
    "            try:\n",
    "                res = selector(kline)\n",
    "                if res['is_match']:\n",
    "                    results.append(res)\n",
    "            except:\n",
    "                continue\n",
    "    except:\n",
    "        traceback.print_exc()\n",
    "        print(\"fail on: {}\".format(symbol))\n",
    "\n",
    "print(\"选股结果：\")\n",
    "df = pd.DataFrame(results)\n",
    "print(df)\n",
    "# df.to_excel(\"选股结果.xlsx\", index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
